package com.snail.ddclock

import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import com.snail.commons.entity.PermissionsRequester
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), PermissionsRequester.OnRequestResultListener {
    private var permissionsRequester: PermissionsRequester? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initialize()
        val intent = Intent(this, TimerService::class.java)
        startService(intent)
        bindService(intent, object : ServiceConnection {
            override fun onServiceDisconnected(name: ComponentName?) {
            }

            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            }
        }, Context.BIND_AUTO_CREATE)
        btnOpenDingDing.setOnClickListener {
            val i = packageManager.getLaunchIntentForPackage("com.alibaba.android.rimet")
            if (i != null) {
                startActivity(i)
                MyApplication.sendTextMail()
            }
        }
    }

    private fun initialize() {
        //动态申请权限
        permissionsRequester = PermissionsRequester(this)
        permissionsRequester?.setOnRequestResultListener(this)
        permissionsRequester?.checkAndRequest(getNeedPermissions())
    }

    //需要进行检测的权限
    private fun getNeedPermissions(): MutableList<String> {
        val list = java.util.ArrayList<String>()
        list.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        list.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        list.add(Manifest.permission.READ_PHONE_STATE)
        return list
    }

    //权限申请结果，参数返回
    override fun onRequestResult(refusedPermissions: MutableList<String>) {
        
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        permissionsRequester?.onActivityResult(requestCode)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissionsRequester?.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun onBackPressed() {
        val home = Intent(Intent.ACTION_MAIN)
        home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        home.addCategory(Intent.CATEGORY_HOME)
        startActivity(home)
    }
}
